package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    private static final Long BEGIN_TIME = 1672531200L;
    private int TIME_BITS = 32;

    public long nextId(String keyPrefix) {
        // 1. 生成时间戳
        LocalDateTime now = LocalDateTime.now();
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIME;
        // 2. 生成序列号
        Long n = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + date);
        // 3. 生成最终的ID
        long resultID = timestamp << TIME_BITS | n;
        return resultID;
    }

    // public static void main(String[] args) {
    //     LocalDateTime time = LocalDateTime.of(2023, 1, 1, 0, 0, 0);
    //     long second = time.toEpochSecond(ZoneOffset.UTC);
    //     System.out.println(second);
    // }
}
